package com.witmore.neutron.ai.web.apiv2.stock;

import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeParam;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeResponse;
import com.witmore.neutron.ai.web.wechat.dto.QrCodeResult;
import com.witmore.neutron.ai.web.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * V2 微信相关控制器
 * Author: 豆子高
 * Date: 2025/12/19
 */
@Slf4j
@RestController
@RequestMapping("/v2/wechat")
public class WechatControllerV2 {

    @Autowired
    private WechatService wechatService;

    private final static String FR_DEFAULT = "default";

    /**
     * 生成带参数的二维码
     */
    @PostMapping("/create-qrcode")
    public ResponseResult<QrCodeResult> createQrCode(@RequestBody CreateQrCodeParam param) {
        if (!StringUtils.hasText(param.getFr())) {
            param.setFr(FR_DEFAULT);
        }
        param.setSceneValue(GlobalAccountSession.getUserInfo().getUserPhone() + "_" + param.getFr());

        try {
            // 生成唯一的场景值，可以包含业务参数
            String sceneStr = param.getSceneValue() + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            log.info("生成二维码场景值：{}", sceneStr);
            CreateQrCodeResponse response = wechatService.createQrCode(sceneStr, param.getExpireSeconds());

            if (response != null && StringUtils.hasText(response.getTicket())) {
                QrCodeResult result = new QrCodeResult();
                result.setTicket(response.getTicket());
                result.setUrl(response.getUrl());
                result.setSceneStr(sceneStr);
                result.setImageUrl(wechatService.getQrCodeImageUrl(response.getTicket()));
                result.setExpireSeconds(response.getExpireSeconds());

                return ResponseResult.success(result);
            } else {
                return ResponseResult.fail(500, "生成二维码失败");
            }
        } catch (Exception e) {
            log.error("生成微信二维码异常", e);
            return ResponseResult.fail(500, "生成二维码异常");
        }
    }



}
